package com.hxut.servlet;

import com.hxut.dao.UserDao;
import com.hxut.model.Goods;
import com.hxut.model.User;
import com.hxut.utils.JdbcUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet(name ="LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remembers = req.getParameter("remembers");

        UserDao userDao = new UserDao();
        User user = userDao.findUserByNameAndPs(username,password);

        if (remembers!=null && remembers.equals("true")){
            Cookie cookie1 = new Cookie("username", username);
            Cookie cookie2 = new Cookie("password", password);
            resp.addCookie(cookie1);
            resp.addCookie(cookie2);
        }

        if(user!=null && user.getUsername()!=null){
            HttpSession session= req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect(req.getContextPath()+"/user_center.jsp");
        }else {
            req.setAttribute("message","用户名或密码错误");
            RequestDispatcher dispatcher =req.getRequestDispatcher("login.jsp");
            dispatcher.forward(req, resp);
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
